﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Rehabilitation.Models;

namespace Rehabilitation.Controllers
{
    public class TestController : Controller
    {
        private DBEntities db = new DBEntities();

        public List<string> resultStrs = new List<string>() { "0", "1", "2", "3", "4", "5", "6", "_1", "_2", "_3" };

        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);

            if (!Request.IsAuthenticated || Session["User"] == null)
            {
                Response.Redirect("/Account/LogOff");
            }
        }


        //
        // GET: /Test/

        public ActionResult Index()
        {
            return View(db.Tests.ToList());
        }

        //
        // GET: /Test/Details/5

        public ActionResult Details(long id = 0)
        {
            Test test = db.Tests.Single(t => t.TestID == id);
            if (test == null)
            {
                return HttpNotFound();
            }
            ViewBag.Location = db.Locations.Single(l => l.LocationID == test.Location);
            ViewBag.User = db.Users.Single(u => u.UserId.Equals(test.UserID));
            ViewBag.TestDetails = db.TestDetails.Where(t => t.TestID == id).ToList();
            return View(test);
        }

        //
        // GET: /Test/Create

        public ActionResult Create(long id = 0)
        {
            Patient patient = db.Patients.Single(p => p.PatientID == id);
            if (patient == null)
            {
                return HttpNotFound();
            }
            ViewBag.Patient = patient;
            List<Location> locations = db.Locations.ToList();
            if(locations.Any())
            {
                List<SelectListItem> locationList = new List<SelectListItem>();
                foreach (Location location in locations)
                {
                    locationList.Add(new SelectListItem(){Text = location.Name, Value = location.LocationID.ToString()});
                }
                ViewBag.LocationList = locationList;
            }
            
            ViewBag.UserID = ((User) Session["User"]).UserId;
            return View();
        }

        //
        // POST: /Test/Create

        [HttpPost]
        public ActionResult Create(Test test)
        {
            if (ModelState.IsValid)
            {
                db.Tests.AddObject(test);
                db.SaveChanges();
                return RedirectToAction("Details", new{id=test.TestID});
            }
            ViewBag.UserID = ((User) Session["User"]).UserId;
            return View(test);
        }

        //
        // GET: /Test/Edit/5

        public ActionResult Edit(long id = 0)
        {
            Test test = db.Tests.Single(t => t.TestID == id);
            if (test == null)
            {
                return HttpNotFound();
            }
            List<Location> locations = db.Locations.ToList();
            if (locations.Any())
            {
                List<SelectListItem> locationList = new List<SelectListItem>();
                foreach (Location location in locations)
                {
                    locationList.Add(new SelectListItem() { Text = location.Name, Value = location.LocationID.ToString() });
                }
                ViewBag.LocationList = locationList;
            }
            return View(test);
        }

        //
        // POST: /Test/Edit/5

        [HttpPost]
        public ActionResult Edit(Test test)
        {
            if (ModelState.IsValid)
            {
                db.Tests.Attach(test);
                db.ObjectStateManager.ChangeObjectState(test, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Details", new { id = test.TestID });
            }
            return View(test);
        }

        //
        // GET: /Test/Delete/5

        public ActionResult Delete(long id = 0)
        {
            Test test = db.Tests.Single(t => t.TestID == id);
            if (test == null)
            {
                return HttpNotFound();
            }
            return View(test);
        }

        //
        // POST: /Test/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(long id)
        {
            Test test = db.Tests.Single(t => t.TestID == id);
            db.Tests.DeleteObject(test);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        public ActionResult SaveDetails()
        {
            string testIdStr = Request.Params["TestID"];
            if(string.IsNullOrEmpty(testIdStr))
            {
                return HttpNotFound();
            }
            try
            {
                long testId = long.Parse(testIdStr);
                Test test = db.Tests.Single(t => t.TestID == testId);
                if(test!=null)
                {
                    List<TestDetail> tds = db.TestDetails.Where(t => t.TestID == testId).ToList();
                    
                    for(int i = 0 ; i<10; i++)
                    {
                        int sequence = i < 7 ? i : (-i + 6);
                        TestDetail td = tds.SingleOrDefault(t => t.TestSequence == sequence);
                        bool newRecord = (td == null);
                        if(newRecord) td=new TestDetail();
                        string resultStr = resultStrs[i];
                        td.SpO2 = Request.Params["SpO2" + resultStr];
                        td.HR = Request.Params["HR" + resultStr];
                        td.Oxygen = Request.Params["Oxygen" + resultStr];
                        td.Rest = Request.Params["Rest" + resultStr];
                        td.BORG = Request.Params["BORG" + resultStr];
                        td.Comments = Request.Params["Comments" + resultStr];
                        td.TestSequence = sequence;
                        td.TestID = test.TestID;
                        if(newRecord)db.TestDetails.AddObject(td);
                        db.SaveChanges();
                    }
                    return RedirectToAction("Details", new {id = test.TestID});
                }
            }catch(Exception ex)
            {
                ViewBag.Message = ex;
                return HttpNotFound();
            }
            return HttpNotFound();
        }

    }
}